import { useEffect, useReducer, useState } from 'react';
import { loc_week } from 'sui';

// the current date and time
// update per 1s
const useDate = () => {
    const [d, t] = loc_week();

    const [date, setDate] = useState(d);
    const [time, setTime] = useState(t);

    useEffect(() => {
        const id = setInterval(() => {
            const [cd, ct] = loc_week();
            setDate(cd);
            setTime(ct);
        }, 1000);

        return () => clearInterval(id);
    }, []);

    return [date, time];
}

// timer for time's second, example:
/*
    const reducer = (state, action) => {
        if (action.type === "update") {
            handleR();
        }

        return state;
    }

    useTimer(reducer);
*/
const useTimer = (reducer, tick=1000, type="update", data=null, scan=true) => {
    const [state, dispatch] = useReducer(reducer, {data: data});

    useEffect(() => {
        if (!scan) {
            return;
        }

        const id = setInterval(() => dispatch({type: type}), tick);
        return () => clearInterval(id);
    }, [tick, type, scan]);

    return [state, dispatch];
};

const scroll_id = (id) => {
    if (!id) {
        return;
    }

    const cp = document.getElementById(id);
    if (!cp) {
        return;
    }

    cp.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
    });
};

export {scroll_id, useDate, useTimer};
